package util;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.NoSuchAlgorithmException;

/**
 * @Description 文件工具类
 * @Author 冷彭磊
 * @Data 2025/2/26 8:56
 */
public class FileUtils {

    //获取文件长度
    public long getFileLength(String fileUrl) throws IOException {
            HttpURLConnection con =(HttpURLConnection) new URL(fileUrl).openConnection();
            con.setConnectTimeout(10000);
            con.setRequestMethod("HEAD");
            long fileLength = con.getContentLengthLong();
            con.disconnect();
            return fileLength;

    }

    //文件是否存在
    public boolean isFileExist(String saveFile,String MD5){
        File file = new File(saveFile);
        try {
            if (file.exists() &&  Md5Utils.calculateMd5(file).equals(MD5) ){
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return false;

    }

    //检查文件是否支持断点续传
    public boolean isBreakpointContinuation(String fileUrl) {
        HttpURLConnection con = null;
        try {
            URL url = new URL(fileUrl);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("HEAD");
            con.setReadTimeout(5000);
            //禁止跳转
            con.setInstanceFollowRedirects(false);

            //检查Accept-Ranges头
            String acceptRanges = con.getHeaderField("Accept-Ranges");
            if (acceptRanges != null && acceptRanges.equalsIgnoreCase("bytes")) {
                return true;
            }

            //检查返回值是否为206
            con.disconnect();
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Range", "bytes=0-0");
            int responseCode = con.getResponseCode();
            return responseCode == HttpURLConnection.HTTP_PARTIAL;

        } catch (IOException e) {
            throw new RuntimeException("检查文件是否支持断点续传失败", e);
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
    }

}




